﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using QuanLyNhaSach;
using QuanLyNhaSach.BusinessLogicLayer;
using System.Collections;


namespace QuanLyBaoCao_NS
{
    public partial class QuanLyBaoCao : Form
    {
        string thangHienTai;
        string namHienTai;
        QuanLyBaoCaoBLL qlbc = new QuanLyBaoCaoBLL();

        StringFormat strFormat; //Used to format the grid rows.
        ArrayList arrColumnLefts = new ArrayList();//Used to save left coordinates of columns
        ArrayList arrColumnWidths = new ArrayList();//Used to save column widths
        int iCellHeight = 0; //Used to get/set the datagridview cell height
        int iTotalWidth = 0; //
        int iRow = 0;//Used as counter
        bool bFirstPage = false; //Used to check whether we are printing first page
        bool bNewPage = false;// Used to check whether we are printing a new page
        int iHeaderHeight = 0; //Used for the header height
        Font fontTieuDe = new Font("Times New Roman", 15, FontStyle.Bold);
        Font fontThoiGian = new Font("Times New Roman", 13, FontStyle.Italic);
        Font fontNoiDung = new Font("Times New Roman", 13, FontStyle.Regular);
        

        public QuanLyBaoCao()
        {
            InitializeComponent();
            thangHienTai = monthCalendar.SelectionRange.Start.Month.ToString();
            label_thangBC.Text = "Tháng: " + thangHienTai;
            monthCalendar.MaxSelectionCount = 1;
            dataGridView.Font = fontNoiDung;            
        }
        
        private void link_BCCN_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            HienThiTenVaThangBC("BÁO CÁO CÔNG NỢ");
            link_BCCN.LinkColor = Color.Red;
            link_BCT.LinkColor = Color.Blue;
            button_inBC.Enabled = true;
            dataGridView.Columns[1].HeaderText = "Khách Hàng";
            dataGridView.Columns[2].HeaderText = "Nợ Đầu";
            dataGridView.Columns[3].HeaderText = "Phát Sinh";
            dataGridView.Columns[4].HeaderText = "Nợ Cuối";

            int x = qlbc.TinhCongNo(thangHienTai + "/01/" + namHienTai);
            for (int i = 0; i < x; i++)
            {
                dataGridView.Rows.Add(qlbc.TaiCongNo(i));
            }
        }

        private void link_BCT_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            HienThiTenVaThangBC("BÁO CÁO TỒN");
            link_BCCN.LinkColor = Color.Blue;
            link_BCT.LinkColor = Color.Red;
            button_inBC.Enabled = true;
            
            dataGridView.Columns[1].HeaderText = "Mã Sách";
            dataGridView.Columns[2].HeaderText = "Tồn Đầu";
            dataGridView.Columns[3].HeaderText = "Phát Sinh";
            dataGridView.Columns[4].HeaderText = "Tồn Cuối";

            int x = qlbc.TinhTonKho(thangHienTai + "/01/" + namHienTai);            
            for (int i = 0; i < x; i++)
            {
                dataGridView.Rows.Add(qlbc.TaiTonKho(i));
            }
        }

        private void HienThiTenVaThangBC(string tenBC)
        {
            label_ten_BC.Text = tenBC;
            thangHienTai = monthCalendar.SelectionRange.Start.Month.ToString();
            namHienTai = monthCalendar.SelectionRange.Start.Year.ToString();            
            label_thangBC.Text = "Tháng: " + thangHienTai;
            dataGridView.Rows.Clear();
        }

        private void button_inBC_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog printDialog = new PrintPreviewDialog();
            printDocument.DocumentName = label_ten_BC.Text + " " + label_thangBC.Text;
            printDialog.Document = printDocument;
            printDialog.ShowDialog();
        }

        private void monthCalendar_DateChanged(object sender, DateRangeEventArgs e)
        {
            thangHienTai = monthCalendar.SelectionRange.Start.Month.ToString();
        }

        private void printDocument_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            try
            {
                strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Near;
                strFormat.LineAlignment = StringAlignment.Center;
                strFormat.Trimming = StringTrimming.EllipsisCharacter;

                arrColumnLefts.Clear();
                arrColumnWidths.Clear();
                iCellHeight = 0;
                iRow = 0;
                bFirstPage = true;
                bNewPage = true;

                // Calculating Total Widths
                iTotalWidth = 0;
                foreach (DataGridViewColumn dgvGridCol in dataGridView.Columns)
                {
                    iTotalWidth += dgvGridCol.Width;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            try
            {
                //canh lề trái
                int iLeftMargin = e.MarginBounds.Left;
                //canh lề trên
                int iTopMargin = e.MarginBounds.Top;
                //kiểm tra có nhiều trang in hay không
                bool bMorePagesToPrint = false;
                int iTmpWidth = 0;

                //in trang đầu
                if (bFirstPage)
                {
                    foreach (DataGridViewColumn GridCol in dataGridView.Columns)
                    {
                        iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
                                       (double)iTotalWidth * (double)iTotalWidth *
                                       ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                        iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                                    GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

                        // Save width and height of headres
                        arrColumnLefts.Add(iLeftMargin);
                        arrColumnWidths.Add(iTmpWidth);
                        iLeftMargin += iTmpWidth;
                    }
                }
                //Loop till all the grid rows not get printed
                while (iRow <= dataGridView.Rows.Count - 1)
                {
                    DataGridViewRow GridRow = dataGridView.Rows[iRow];
                    //Set the cell height
                    iCellHeight = GridRow.Height + 5;
                    int iCount = 0;
                    //Check whether the current page settings allo more rows to print
                    if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                    {
                        bNewPage = true;
                        bFirstPage = false;
                        bMorePagesToPrint = true;
                        break;
                    }
                    else
                    {
                        if (bNewPage)
                        {
                            //tiêu đề
                            //tên bc
                            e.Graphics.DrawString(label_ten_BC.Text.ToUpper(), fontTieuDe, Brushes.Black,
                                e.MarginBounds.Left, e.MarginBounds.Top -
                                    e.Graphics.MeasureString(label_ten_BC.Text.ToUpper(), fontTieuDe, e.MarginBounds.Width).Height - 13
                                    - e.Graphics.MeasureString(label_thangBC.Text, fontNoiDung, e.MarginBounds.Width).Height - 13);
                            //tháng bc
                            e.Graphics.DrawString(label_thangBC.Text, fontNoiDung, Brushes.Black,
                                e.MarginBounds.Left, e.MarginBounds.Top
                                    - e.Graphics.MeasureString(label_ten_BC.Text.ToUpper(), fontTieuDe, e.MarginBounds.Width).Height - 13);


                            String strDate = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
                            //ngày in
                            e.Graphics.DrawString(strDate, fontThoiGian,
                                    Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
                                    e.Graphics.MeasureString(strDate, fontThoiGian, e.MarginBounds.Width).Width), e.MarginBounds.Top -
                                    e.Graphics.MeasureString(label_thangBC.Text, fontThoiGian, e.MarginBounds.Width).Height - 13);

                            //nội dung             
                            iTopMargin = e.MarginBounds.Top;
                            foreach (DataGridViewColumn GridCol in dataGridView.Columns)
                            {
                                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawRectangle(Pens.Black,
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font,
                                    new SolidBrush(GridCol.InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                                iCount++;
                            }
                            bNewPage = false;
                            iTopMargin += iHeaderHeight;
                        }
                        iCount = 0;
                        //Draw Columns Contents                
                        foreach (DataGridViewCell Cel in GridRow.Cells)
                        {
                            if (Cel.Value != null)
                            {
                                e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
                                            new SolidBrush(Cel.InheritedStyle.ForeColor),
                                            new RectangleF((int)arrColumnLefts[iCount], (float)iTopMargin,
                                            (int)arrColumnWidths[iCount], (float)iCellHeight), strFormat);
                            }
                            //Drawing Cells Borders 
                            e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrColumnLefts[iCount],
                                    iTopMargin, (int)arrColumnWidths[iCount], iCellHeight));

                            iCount++;
                        }
                    }
                    iRow++;
                    iTopMargin += iCellHeight;
                }

                //If more lines exist, print another page.
                if (bMorePagesToPrint)
                    e.HasMorePages = true;
                else
                    e.HasMorePages = false;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
